/*****************************************************************************/
exports.functions={
	admin_pages_load: function(space,level,parent_id) {
		level=level||0;
		parent_id=parent_id||0;
//		var aref=space.site.sql.execute_and_fetch("pages/list_admin",{parent_id:parent_id});
		var aref=space.mfact.list("page",{parent_id:parent_id==0?{type:"null"}:parent_id,order_by:"main.ordering"});
		aref.forEach(function(item) {
			item.level=level;
			item.children=space.functions.admin_pages_load(space,level+1,item.id);
		});
		return aref;
	},

	gdbe_styles_loader: function(space,filter) {
		space.gdbe_styles=[];
		if (!filter) filter={order_by:"main.ordering"};
		space.mfact.list("gdbe_style",filter).forEach(function(a) {
			var gdbes={id:a.id,name:a.name};
			gdbes.blocks=space.mfact.list("gdbe_style_block",{order_by:"main.ordering",style_id:gdbes.id});
			space.gdbe_styles.push(gdbes);
		});
	},

	gdbe_document_load: function(space,table,column,id,value) {
		var grp=space.mfact.get("gdbe_source_group",{table_name:table,column_name:column});
		if (!grp) return undefined;
		var src=space.mfact.get("gdbe_source",{group_id:grp.id,fid:id});
		if (!src) return undefined;
		return src.source;
	},

	/*
		params: object of:
			params.no_save - optional, flag to not save data to database, defaults to 0
			params.max_blocks - optional, maximum number of blocks translate, defaults to undefined
	*/
	gdbe_document_save: function(space,table,column,id,value,params) {
		if (!params) params={};
		var decode=JSON.parse(value);
		if (!params.no_save) {
			var grp=space.mfact.get("gdbe_source_group",{table_name:table,column_name:column});
			if (!grp) {
				grp=space.mfact.from_object("gdbe_source_group",{table_name:table,column_name:column});
				grp.Save();
			}
			var src=space.mfact.get("gdbe_source",{group_id:grp.id,fid:id});
			if (src) {
				src.source=value;
			} else {
				src=space.mfact.from_object("gdbe_source",{group_id:grp.id,fid:id,source:value});
			}
			src.Save();
		}
		var blocks={};
		space.mfact.list("gdbe_style_block",{style_id:decode.style_id}).forEach(function(b) { blocks[b.id]=b; });
		var compiled="";
		var cnt=decode.value.length;
		if (params.max_blocks && cnt>params.max_blocks) cnt=params.max_blocks;
		for (var i=0;i<cnt;i++) {
			var v=decode.value[i];
			compiled+=space.views.apply(blocks[v.block_id].result_html,v);
		}
		return compiled;
	}
}

/*****************************************************************************/
exports.controllers={
	admin_pages: function(space) {
		if (!space.roles.pages) return "Access denied";
		var mode=space.fields.mode||"list";
		return space.controllers['admin_pages__'+mode](space);
	},

	admin_pages__translit: function(space) {
		var s=space.functions.to_latin(space,space.fields.value);
		return s;
	},	
	admin_pages__list: function(space) {
		space.current_pages=space.functions.admin_pages_load(space);
//		space.current_pages=space.mfact.list_hier("page",{});
		return space.views.process("widgets/admin_pages/list",space);
	},
	
	admin_pages__list_recurse: function(space) {
		if (space.cpage.children.length==0) return "";
		space.current_pages=space.cpage.children;
		var r=space.views.process("widgets/admin_pages/list_item",space);
		return r;
	},
	
	admin_pages__reorder: function(space) {
		var pages=[];
		var page_orders=[];
		space.fields.pages.split(/,/).forEach(function(page_id) {
			page_id=page_id.replace(/page-/,'');
			pages.push(page_id);
			var ord=space.site.sql.execute_and_fetch_one("pages/get_ordering",{page_id:page_id})["ordering"]*1;
			page_orders.push(ord);
			space.site.sql.execute("pages/set_ordering",{page_id:page_id,ordering:-ord});
		});
		page_orders.sort(function(a,b){return a - b});
		var i=0;
		var r={orderings:{},pages:[]};
		pages.forEach(function(page_id) {
			r.pages.push(page_id);
			r.orderings[page_id]=page_orders[i];
			space.site.sql.execute("pages/set_ordering",{page_id:page_id,ordering:page_orders[i]});
			i++;
		});
		throw space.Dumper({pages:pages,page_orders:page_orders,r:r});
		return JSON.stringify(r);
	},
	
	admin_pages__edit: function(space) {
		space.pages=[{id:"",name:""}].concat(space.site.sql.execute_and_fetch_h("pages/list_admin_fkey",{not_page_id:(space.fields.page_id||0)}));
		space.templates=[{id:"",name:""}].concat(space.site.sql.execute_and_fetch("templates/list"));
		space.roles=[{id:"",name:""}].concat(space.site.sql.execute_and_fetch("roles/list"));
		space.tplaces={};
		space.functions.gdbe_styles_loader(space);
		space.templates.forEach(function(t) {
			if (t.id=="") {
				t.places=[];
			} else {
				space.tplaces[t.id]=t.places=space.site.sql.execute_and_fetch("template_places/list",{template_id:t.id});
			}
		});
		if (space.fields.page_id) {
//			var tpsinfo={};
//			space.site.sql.execute_and_fetch("template_places/list",{template_id:space.fields.template_id}).forEach(function(tp) { tpsinfo[tp.id]=tp; });
			space.cpage=space.site.sql.execute_and_fetch_one("pages/get");
			space.cpage_blocks={};
			space.site.sql.execute_and_fetch("page_blocks/list").forEach(function(pb) {
				if (pb.place_type_code=="gdbe" || pb.place_type_code=="tmplgdbe") {
					for (var k in pb) {
						if (k=="place_code" || k=="id" || k=="place_type_code" || k=="place_admin_height" || k=="page_id" || k=="place_id") continue;
						var tmp=space.functions.gdbe_document_load(space,"tpages","page_block_"+pb.place_id,space.fields.page_id);
						if (tmp!=undefined) pb[k]=tmp;
					}
				}
				space.cpage_blocks[pb.place_code]=pb;
			});
		} else {
			space.cpage={};
			space.cpage_blocks={};
		}
		space.inputs_name=[];
		space.inputs_ktsd=[];
		var mlang=space.site.multiple_languages||[""];
		mlang.forEach(function(l) {
			space.inputs_name.push({language: l,value: l==""?space.cpage.name:space.cpage["name_"+l],name: l==""?"name":"name_"+l});
			["keywords","title","subject","description"].forEach(function(x) {
				space.inputs_ktsd.push({name:l==""?x:x+"_"+l,language: l,value: l==""?space.cpage[x]:space.cpage[x+"_"+l],label: space.functions.L(space,"widgets/admin_pages/edit","field_"+x)});
			});
		});
		return space.views.process("widgets/admin_pages/edit",space);
	},
	
	admin_pages__save_only: function(space) {
		var ret=space.controllers.admin_pages__save(space);
		return JSON.stringify({call:"ajajform_frm_set_id",name:"page_id",id:space.fields.page_id});
//		return JSON.stringify({});
	},

	admin_pages__save: function(space) {
		var page;
		if (space.fields.page_id && space.fields.page_id!="") {
			page=space.mfact.get("page",space.fields.page_id);
			page.UpdateFromObject(space.fields);
			page.Save();
//			space.site.sql.execute("pages/update");
			space.site.sql.execute("page_blocks/delete_of_page");
		} else {
			page=space.mfact.from_object("page",space.fields);
			page.Save();
			space.fields.page_id=page.id;
		}
		var pbs={};
		var tpsinfo={};
		space.site.sql.execute_and_fetch("template_places/list",{template_id:space.fields.template_id}).forEach(function(tp) { tpsinfo[tp.id]=tp; });
		function possible_gdbe(tpid,col,body) {
			if (tpsinfo[tpid].place_type_code=="gdbe" || tpsinfo[tpid].place_type_code=="tmplgdbe") return space.functions.gdbe_document_save(space,"tpages",col,page.id,body);
			return body;
		}
		for (var p in space.fields) {
			var arr;
			if (arr=p.match(/^block_(\d+)$/)) {
				pbs[arr[1]]={body: possible_gdbe(arr[1],"page_block_"+arr[1],space.fields[p])};
			} else if (arr=p.match(/^block_(\d+)_(\w+)$/)) {
				if (!pbs[arr[1]]) pbs[arr[1]]={};
				pbs[arr[1]]["body_"+arr[2]]=possible_gdbe(arr[1],"page_block_"+arr[1]+"_"+arr[2],space.fields[p]);
			}
		}
		for (var tpid in pbs) {
			var h=pbs[tpid];
			h.page_id=page.id;
			h.place_id=tpid;
			var pb=space.mfact.from_object("page_block",h);
			pb.Save();
		}
/*		for (var p in space.fields) {
			var arr;
			if (!(arr=p.match(/^block_(\w+)$/))) continue;
			space.site.sql.execute("page_blocks/insert",{code:arr[1],body:space.fields[p]});
		}*/
		return JSON.stringify({redirect:{url:space.action}});
	},
	
	admin_pages__delete: function(space) {
		space.cpage=space.site.sql.execute_and_fetch_one("pages/get");
		return space.views.process("widgets/admin_pages/delete",space);
	},
	
	admin_pages__delete_save: function(space) {
		space.site.sql.execute("page_blocks/delete_of_page");
		space.site.sql.execute("pages/delete");
		return JSON.stringify({redirect:{url:space.action}});
	}
};

/*****************************************************************************/
